#!/bin/bash
# VimL虚拟机 Debug版本构建脚本

echo "VimL虚拟机 Debug版本构建"
echo "=========================="
echo ""

# 设置构建参数
BUILD_DIR="build"
CMAKE_BUILD_TYPE="Debug"
CMAKE_CXX_FLAGS_Debug="-O0 -DDEBUG -march=native"
CMAKE_EXE_LINKER_FLAGS_Debug="-pg -g"

echo "构建配置:"
echo "  构建目录: $BUILD_DIR"
echo "  构建类型: $CMAKE_BUILD_TYPE"
echo "  编译器标志: $CMAKE_CXX_FLAGS_Debug"
echo "  链接器标志: $CMAKE_EXE_LINKER_FLAGS_Debug"
echo ""

# 清理旧构建
if [ -d "$BUILD_DIR" ]; then
    echo "清理旧的构建目录..."
    rm -rf "$BUILD_DIR"
fi

# 创建构建目录
mkdir -p "$BUILD_DIR"
cd "$BUILD_DIR"

# 配置CMake
echo "配置CMake..."
cmake -G Ninja \
    -DCMAKE_BUILD_TYPE="$CMAKE_BUILD_TYPE" \
    -DCMAKE_CXX_FLAGS="$CMAKE_CXX_FLAGS_Debug" \
    -DCMAKE_EXE_LINKER_FLAGS="$CMAKE_EXE_LINKER_FLAGS_Debug" \
    ..

if [ $? -ne 0 ]; then
    echo "CMake配置失败!"
    exit 1
fi

# 构建
echo ""
echo "开始构建..."
ninja -j$(nproc)

if [ $? -ne 0 ]; then
    echo "构建失败!"
    exit 1
fi

# 优化二进制文件
echo ""
echo "优化二进制文件..."
strip bin/vimlc

# 显示构建结果
echo ""
echo "构建完成!"
echo "=========="
echo "二进制文件位置: $(pwd)/bin/vimlc"
echo "二进制文件大小: $(ls -lh bin/vimlc | awk '{print $5}')"
echo ""

# 快速性能测试
echo "快速性能测试 - Fib(20):"
cat > ../temp_quick_test.vim << 'EOF'
function Fib(n)
  if n < 2
    return n
  else
    return Fib(n-1) + Fib(n-2)
  endif
endfunction

echo Fib(20)
EOF

time ./bin/vimlc ../temp_quick_test.vim
rm -f ../temp_quick_test.vim

echo ""
echo "Debug版本构建完成!"
echo "可以使用 './build/bin/vimlc' 运行VimL程序"